home *** CD-ROM | disk | FTP | other *** search
/ Turnbull China Bikeride / Turnbull China Bikeride - Disc 2.iso / BARNET / FREENET / MELL / NETLIB00 / NetLib / c / addr next >
Text File  |  1995-02-28  |  1KB  |  58 lines

  1. #include <stdio.h>
  2.  
  3. #include "arpa/inet.h"
  4. #include "netinet/in.h"
  5.  
  6. /*
  7.  * Extract an internet address in network byte order from a string
  8.  */
  9. u_long inet_addr(const char *cp)
  10. {
  11.   u_long octet1;
  12.   u_long octet2;
  13.   u_long octet3;
  14.   u_long octet4;
  15.   int    octets;
  16.  
  17.   /* Parse the string */
  18.   octets = sscanf(cp, "%i.%i.%i.%i", (int *)&octet1, (int *)&octet2,
  19.                   (int *)&octet3, (int *)&octet4);
  20.  
  21.   switch (octets)
  22.   {
  23.     case 1:
  24.       /* Address is in 'a' format so break it up 'a' */
  25.       octet4 = octet1 & 0xff;
  26.       octet3 = (octet1 >> 8) & 0xff;
  27.       octet2 = (octet1 >> 16) & 0xff;
  28.       octet1 = (octet1 >> 24) & 0xff;
  29.       break;
  30.     case 2:
  31.       /* Address is in 'a.b' format so break up 'b' */
  32.       octet4 = octet2 & 0xff;
  33.       octet3 = (octet2 >> 8) & 0xff;
  34.       octet2 = (octet2 >> 16) & 0xff;
  35.       break;
  36.     case 3:
  37.       /* Address is in 'a.b.c' format so break up 'c' */
  38.       octet4 = octet3 & 0xff;
  39.       octet3 = (octet3 >> 8) & 0xff;
  40.       break;
  41.     case 4:
  42.       /* Address is in 'a.b.c.d' format so leave it as is */
  43.       break;
  44.     default:
  45.       /* Error */
  46.       return (u_long)-1;
  47.   }
  48.  
  49.   /* Validate the octet values */
  50.   if (octet1 > 255 || octet2 > 255 || octet3 > 255 || octet4 > 255)
  51.   {
  52.     return (u_long)-1;
  53.   }
  54.  
  55.   /* Put the address together */
  56.   return (octet4 << 24) | (octet3 << 16) | (octet2 << 8) | octet1;
  57. }
  58.